<?php
class Core_Model_Config {

	protected $_data = array();

	protected $_sorted = array();

	public function merge(array $data, $recursive=false) {
		if ($recursive)
			$this->_data = array_merge_recursive($this->_data, $data);
		else
			$this->_data = array_merge($this->_data, $data);
		return $this;
	}

	public function get($path='') {
		if (empty($path)) return $this->_data;
		
		$keys = explode('/', $path);
		$res = $this->_data;
		foreach($keys as $k) {
			if (!isset($res[$k])) return null;
			$res = $res[$k];
		}
		return $res;
	}

	public function set($path, $val) {
		$keys = explode('/', $path);
		$data =& $this->_data;
		foreach($keys as $k) {
			$data =& $data[$k];
		}
		$data = $val;
		return $this;
	}

	public function save($path, $val) {
		// save config to database
	}
	
	public function loadFile($file, $merge=true) {
		if (!is_readable($file)) return $this;
		$config = require($file);
		if ($merge) $this->merge($config, true);
		return $config;
	}

	public function sortConfig($path, $orderBy) {
		if (in_array($path, $this->_sorted)) return $this;
		
		$rows = $this->get($path);
		if (!is_array($rows)) return $this;
		$columns = Mag::helper('Core')->arrayColumn($rows, $orderBy);
		array_multisort($columns, SORT_ASC, $rows);
		$this->set($path, $rows);

		$this->_sorted[] = $path;
		return $this;
	}

	public function loadDb(Core_Model_DB_Connection $connection, $merge=true) {
		// retrive config key/value from db
		$sql = "SELECT path, value FROM ". $connection->getTable('core_config');
		$dbConfig = $connection->fetchPairs($sql);

		// apply config
		$configClass = get_class($this);
		$config = new $configClass();
		foreach($dbConfig as $k => $v)
			$config->set($k, $v);

		if ($merge) $this->merge($config->get());
		return $config->get();
	}

}